package com.catazy.mvvmlib.net.http.interceptor

import com.blankj.utilcode.util.NetworkUtils
import com.catazy.mvvmlib.base.BaseApplication
import com.catazy.mvvmlib.util.NetworkUtil
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 作者: Tao
 * 日期: 2024/1/29
 * 时间: 10:44
 * 描述: 缓存拦截器
 */
class CacheInterceptor(private val day: Int = 7) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        if (!NetworkUtil.isAvailable(BaseApplication.INSTANCE)) {
            request = request.newBuilder()
                .cacheControl(CacheControl.FORCE_CACHE)
                .build()
        }
        val proceed = chain.proceed(request)
        if (!NetworkUtil.isAvailable(BaseApplication.INSTANCE)) {
            val maxAge = 60 * 60
            proceed.newBuilder()
                .removeHeader("Pragma")
                .header("Cache-Control", "public, max-age=$maxAge")
                .build()
        } else {
            val maxStale = 60 * 60 * 24 * day // tolerate 4-weeks stale
            proceed.newBuilder()
                .removeHeader("Pragma")
                .header("Cache-Control", "public, only-if-cached, max-stale=$maxStale")
                .build()

        }
        return proceed
    }
}